<?php

namespace App\Console\Commands\Video;

use App\Models\Digital;
use App\Services\Http;
use App\Services\LogTrait;
use function Couchbase\basicDecoderV1;
use Illuminate\Console\Command;

class Xg extends Command
{
    use LogTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'video:xg';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '西瓜视频';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @throws \Exception
     * @return mixed
     */
    public function handle()
    {
        try{
            $this->logName = $this->signature;
            $http = Http::getInstance();

            $response = $http->request('get', 'https://www.ixigua.com/api/feedv2/feedById', [
                'query' => [
                    '_signature' => 'MbZOwgAgEALf8BGJB5.GcDG2TtAAGzJ',
                    'channelId'  => 61887739369,
                    'count'      => 30,
                    'maxTime'    => 1567943387
                ]
            ]);
            $json = \GuzzleHttp\json_decode($response->getBody()->getContents(), true);
            $data = $json['data']['channelFeed']['Data'];

            foreach ( $data as $key => $row ) {
                $url = 'https://www.ixigua.com/i'.$row['videoId'].'/';
                $response = $http->request('get', $url, [
                    'headers' => [
                        'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
                    ]
                ]);
                $contents = $response->getBody()->getContents();

                preg_match('/.*"vid":"(.*?)".*/', $contents, $match);
                $vid = $match[1];

                preg_match('/.*"title":"(.*?)".*/', $contents, $match);
                $title = $match[1];

                $rand = rand(1000000000000000, 9999999999999999);
                $urlPart = '/video/urls/v/1/toutiao/mp4/'.$vid.'?r='.$rand.'';
                $str = crc32($urlPart);
                $videoUrl = 'https://ib.365yg.com'.$urlPart.'&s='.$str.'';
                $videoRes = $http->request('get', $videoUrl);
                $videoArr = \GuzzleHttp\json_decode($videoRes->getBody()->getContents(), true);

                $videoUrl = base64_decode($videoArr['data']['video_list']['video_1']['main_url']);
                $videoUrl =  urldecode($videoUrl);
                $insertData = [
                    'url' => $videoUrl,
                    'title' => $title,
                    'first_image' => $videoArr['data']['poster_url'],
                    'source'  => 2,
                    'type' => 2,
                ];
                $this->logWrite(json_encode($insertData, JSON_UNESCAPED_UNICODE));
                $this->dataToDb($insertData);
            }

        }catch (\Exception $e){
            $this->logWrite($e->getMessage());
            $this->logWrite($e->getTraceAsString());
        }
    }

    public function dataToDb($data)
    {
        Digital::query()->updateOrCreate([
            'url' => $data['url']
        ],$data);
    }
}
